package com.example.springboot.controller;

import com.example.springboot.common.Result;
import com.example.springboot.entity.User;
import com.example.springboot.entity.request.LoginRequest;
import com.example.springboot.entity.request.PasswordRequest;
import com.example.springboot.entity.request.UserPageRequest;
import com.example.springboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author 程序员小洋
 * @version 2022.3
 * @date 2022/12/8 11:41
 * @title 用户表的控制层
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController {

    @Autowired
    private UserService userService;

    /**
     * 登录
     * @param request
     * @return
     */
    @PostMapping("/login")
    public Result login(@RequestBody LoginRequest request) {
        User user= userService.login(request);
        return Result.success(user);
    }

    @PutMapping("/password")
    public Result password(@RequestBody PasswordRequest request) {
        userService.changePass(request);
        return Result.success();
    }

    /**
     * 查询列表
     * @return
     */
    @GetMapping("/list")
    public Result list() {
        List<User> list = userService.list();
        return Result.success(list);
    }

    /**
     * 分页查询带条件
     * @param pageRequest
     * @return
     */
    @GetMapping("/page")
    public Result page(UserPageRequest pageRequest) {
        return Result.success(userService.pageInfo(pageRequest));
    }

    @DeleteMapping("/delete/{id}")
    public Result delete(@PathVariable Integer id) {
        userService.removeById(id);
        return Result.success();
    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Integer id) {
        User obj = userService.getById(id);
        return Result.success(obj);
    }

    @PutMapping("/update")
    public Result update(@RequestBody User obj) {
        obj.setUpdatetime(new Date());
        userService.updateById(obj);
        return Result.success();
    }

    @PostMapping("/save")
    public Result save(@RequestBody User user) {
        userService.saveMD5(user);
        return Result.success();
    }

    @PostMapping("/account")
    public Result account(@RequestBody User user) {
        userService.handleAccount(user);
        return Result.success();
    }

}
